package com.yogee.topseller.activity.login.view.impl;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yogee.core.utils.AppManager;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.model.bean.SMSbean;
import com.yogee.topseller.activity.login.presenter.RegisterPresenter;
import com.yogee.topseller.activity.login.presenter.ResetPswPresenter;
import com.yogee.topseller.activity.login.view.IRegisterView;
import com.yogee.topseller.activity.login.view.IResetPswView;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.Constants;
import com.yogee.topseller.view.ClearEditText;

import butterknife.BindView;
import butterknife.OnClick;


public class ForgetPswSendCodeActivity extends HttpActivity implements IResetPswView,IRegisterView {

//    @BindView(R.id.phone)
//    ClearEditText phone;
    @BindView(R.id.validate_code)
    ClearEditText validateCode;
    @BindView(R.id.get_code)
    TextView getCode;

    @BindView(R.id.confirm)
    TextView confirm;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.login_title)
    TextView login_title;

    // 倒计时
    private CountDownTimer timer;
    private ResetPswPresenter resetPresenter;

    private RegisterPresenter registerPresenter;
    //生成一个随机数
    private int mRadomNumber = 0;
    private String phoneNum = "";
    private String flag = "";
    private String openid="",name="", headerUrl="",deviceId="",unionid="";

    /**
     * this activity layout res
     * 设置layout布局
     *
     * @return res layout xml id
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_forget_psw_sendcode;
    }


    @Override
    protected void initView() {
        flag = getIntent().getStringExtra("flag");
        flag = getIntent().getStringExtra("flag");
        if(flag.equals(Constants.FLAG_REGIST)){
            tv_title.setText("注册");
        }else if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
            tv_title.setText("忘记密码");
        }else{
            tv_title.setText("关联手机号码");
            login_title.setVisibility(View.GONE);
            openid = getIntent().getStringExtra("openid");
            name = getIntent().getStringExtra("name");
            headerUrl = getIntent().getStringExtra("headerUrl");
            deviceId = getIntent().getStringExtra("deviceId");
            unionid = getIntent().getStringExtra("unionid");
        }
        phoneNum = getIntent().getStringExtra("phoneNum");
        resetPresenter = new ResetPswPresenter(this);
        registerPresenter = new RegisterPresenter(this);
        mRadomNumber = AppUtil.getRandomNumber(4);

        validateCode.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                validateCode.setFocusable(true);
                validateCode.setFocusableInTouchMode(true);
                return false;
            }
        });
        validateCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String code = validateCode.getText().toString().trim();
                if(code.length()>=6){
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                }

            }
        });

    }

    @OnClick({R.id.confirm, R.id.get_code, R.id.back,R.id.login_title,R.id.img_wx})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
//                if (TextUtils.isEmpty(phone.getText().toString())) {
//                    ToastUtils.showToast(this, "手机号码不能为空");
//                } else if (!AppUtil.validatePhone(phone.getText().toString())) {
//                    ToastUtils.showToast(this, "请输入正确的手机号码");
//                } else

                if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
                    MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "forget_yzm_next");

                }else if(flag.equals(Constants.FLAG_REGIST)){
                    MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "reg_yzm_next");

                }else{
                    MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "wx_reg_yzm_next");
                }
                 if (TextUtils.isEmpty(validateCode.getText().toString())){
                    ToastUtils.showToast(this, "请输入验证码");
                } else if (validateCode.getText().toString().length()>=4&&validateCode.getText().toString().length()<=6) {
                     String code_type = Constants.CODE_FIND;

                     if(!flag.equals(Constants.FLAG_FORGETPASSWORD)){
                         code_type = Constants.CODE_REG;
                     }
                     resetPresenter.registSendSMS(phoneNum,validateCode.getText().toString(),code_type);
                } else {
                    ToastUtils.showToast(this, "验证码错误");
                }
                break;
            case R.id.get_code:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                if ("重新发送".equals(getCode.getText().toString())) {
                    mRadomNumber = AppUtil.getRandomNumber(4);
                }

                if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
                    MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "forget_yzm_getCodeBtn");

                }else if(flag.equals(Constants.FLAG_REGIST)){
                    MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "reg_yzm_getCodeBtn");

                }else{
                    MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "wx_reg_yzm_getcode");
                }

                if (validate()) {
                    getCode.setTextColor(getResources().getColor(R.color.gray));
//                    getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                    getCode.setClickable(false);
                    String code_type = Constants.CODE_FIND;

                    if(!flag.equals(Constants.FLAG_FORGETPASSWORD)){
                        code_type = Constants.CODE_REG;
                    }
                    if(pd!=null)
                        pd.show();
                    resetPresenter.sendSMS(phoneNum,code_type);
                }
                break;
            case R.id.back:
                onBackPressed();
                break;
            case R.id.login_title:
                MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "loginBtn","登录");
                startActivity(new Intent(ForgetPswSendCodeActivity.this, LoginActivity.class));
                finish();
                break;
            case R.id.img_wx:
                ToastUtils.showToast(this, "微信操作");
                break;
            default:
                break;
        }
    }


    public Boolean validate() {
//        if (TextUtils.isEmpty(phone.getText())) {
//            ToastUtils.showToast(this, "请输入手机号");
//            return false;
//        } else if (!AppUtil.validatePhone(phone.getText().toString())) {
//            ToastUtils.showToast(this, "请输入正确的手机号");
//            return false;
//        }
        return true;
    }

    public void countDownTimer() {

        if(flag.equals(Constants.FLAG_REGIST)){
            MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "reg_yzm_get_success");
        }else if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
            MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "forget_yzm_get_success");
        }else{
            MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "wx_reg_yzm_get_success");
        }

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                getCode.setText("重新发送" + "(" + millisUntilFinished / 1000 + "s)");
                getCode.setTextColor(getResources().getColor(R.color.gray));
//                getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                getCode.setClickable(false);
            }

            @Override 
            public void onFinish() {
                getCode.setText("重新发送");
                getCode.setTextColor(getResources().getColor(R.color.theme_color));
//                getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1_theme));
                getCode.setClickable(true);
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
    }

    @Override
    public void showMsg(String msg) {
        ToastUtils.showToast(ForgetPswSendCodeActivity.this, msg);
        if(pd!=null)
            pd.dismiss();
        getCode.setText("重新发送");
        getCode.setTextColor(getResources().getColor(R.color.theme_color));
//        getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1_theme));
        getCode.setClickable(true);
        if (timer != null)
            timer.cancel();
    }


    @Override
    public void updatePassword() {
        if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
            MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "forget_inputPwd");
            // 注册
        }else if(flag.equals(Constants.FLAG_REGIST)){
            MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "reg_inputPwd");

        }else{
            MobclickAgent.onEvent(ForgetPswSendCodeActivity.this, "wx_reg_inputpwd");
        }
        startActivity(new Intent(ForgetPswSendCodeActivity.this, ResetPsActivity.class)
                .putExtra("phoneNum",phoneNum)
                .putExtra("flag",flag)
                .putExtra("openid",openid)
                .putExtra("unionid",unionid)
                .putExtra("name",name)
                .putExtra("headerUrl",headerUrl)
                .putExtra("deviceId",deviceId)) ;
    }

    @Override
    public void updateSuccess() {
//        this.finish();
        if(pd!=null)
            pd.dismiss();

        countDownTimer();
    }

    @Override
    public void updateCheckCode(SMSbean smSbean) {
        if (Integer.parseInt(smSbean.getError_code()) == 0) {
            countDownTimer();
            ToastUtils.showToast(this, "验证码已经发送");
        } else {
            getCode.setClickable(true);
            ToastUtils.showToast(this, smSbean.getError_code() + ":" + smSbean.getReason());
        }
    }

    @Override
    public void newUserRegistration() {

    }

    @Override
    public void registerSuccess(String userId,String flags,String day) {

    }

    @Override
    public void checkCode(SMSbean smSbean) {
        if (Integer.parseInt(smSbean.getError_code()) == 0) {
            countDownTimer();
            ToastUtils.showToast(this, "验证码已经发送");
        } else {
            getCode.setClickable(true);
            ToastUtils.showToast(this, smSbean.getError_code() + ":" + smSbean.getReason());
        }

    }

    @Override
    public void returnCheck() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
